import React from 'react' ; 
import {
    Tools,
    Bubble,
    Modal,
} from "weaver-mobile";
const alert = Modal.alert;
const getLabel = Tools.getLabel;

// code
const doSsoLogin = (params) =>{
    // const {code,msg} = params ;
    // if(code != '1'){
    //     alert(msg);
    //     return ;
    // }

    emSsoLogin() ;
} ;

const emSsoLogin = (params)=>{
    const ps = getUrlkey() ;
    const {redirect_url} = ps ;

    if(window.em && window.em.checkJsApi("ssoLogin")){
    
        Tools.callApi({
            url :'/api/ec/dev/app/getSSOCode',
            method: 'get',
            params: {}
        }).then((ssoRes) => {
            window.em.ssoLogin({
                ssokey: ssoRes.keycode,
                lang_type: ssoRes.langid,
                account: '',
                into: 0,
                success: function (data) {
					 //alert(JSON.stringify(ssoRes));
					let isRememberAccount =ssoRes.isRememberAccount;
					let isRememberPassword =ssoRes.isRememberPassword;
					let cacheAccount =ssoRes.cacheAccount;
					let cachePassword =ssoRes.cachePassword;
					let remember = 1;
					let remembered = {};

					if (isRememberAccount && isRememberAccount=='true') {
						if (isRememberPassword && isRememberPassword=='true') {
							remember = 1;
							remembered = { account:cacheAccount , password: cachePassword };
						} else {
							remember = 2;
							remembered = { account: cacheAccount };
						}
					} else {
						remember = 3;
						remembered = {};
					}
					 //alert('1:'+JSON.stringify(remember));
					 //alert('2:'+JSON.stringify(remembered));
                    if(window.em && window.em.checkJsApi('setItem')){
					   window.em.setItem({ key: 'login-remember', value: JSON.stringify(remember) });
					   window.em.setItem({ key: 'login-remembered', value: JSON.stringify(remembered) });
                    }
                    
					if(window.em && window.em.checkJsApi('pushToMain')){
                        window.em.pushToMain();
                    }else{
                        alert('no support pushToMain');
                    }
                },
                fail: function (err) {
                    alert(err.errMsg, 5);
                    
                },
                complete: function (res) {

                }
            });
        }) ;
    }else if(redirect_url){
        //alert('ceshi');
        window.location.href=redirect_url;
        return ;
    }else{
        alert('em jsapi调用失败>>'+window.em)
    }
}

function getUrlkey(){
    let url = window.location.href ;
    let params = {},
        arr = url.split("?");
    if (arr.length <= 1)
        return params;
    arr = arr[1].split("&");
    for(var i=0, l=arr.length; i<l; i++){
        var a = arr[i].split("=");
        params[a[0]] = a[1];
    }
    return params;
}


setTimeout(function(){
    doSsoLogin() ;
},1000*0.5)